from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.String(50), primary_key=True)
    username = db.Column(db.String(100), nullable=False)
    devices = db.relationship('Device', backref='user', lazy=True)

class Device(db.Model):
    id = db.Column(db.String(50), primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    user_id = db.Column(db.String(50), db.ForeignKey('user.id'), nullable=False)
    status = db.Column(db.String(20), default='offline')  # online/offline/warning/error
    last_active = db.Column(db.DateTime, default=datetime.now)
    battery_level = db.Column(db.Integer, default=100)
    battery_status = db.Column(db.String(20), default='normal')  # normal/low
    sensor_health = db.Column(db.Integer, default=100)
    sensor_health_status = db.Column(db.String(20), default='normal')  # normal/warning/error

class DeviceUsage(db.Model):
    __tablename__ = 'device_usage'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(50), db.ForeignKey('device.id'), nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.now)
    work_duration = db.Column(db.Float, default=0.0)  # 工作时长（小时）
    power_on_count = db.Column(db.Integer, default=0)  # 开机次数
    work_mode = db.Column(db.String(20))  # 工作模式

class DeviceAnomaly(db.Model):
    __tablename__ = 'device_anomalies'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(50), db.ForeignKey('device.id'), nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.now)
    type = db.Column(db.String(50))  # offline/low_battery/sensor_error/hardware_error
    description = db.Column(db.String(200))
    is_resolved = db.Column(db.Boolean, default=False)

class MaintenanceRecord(db.Model):
    __tablename__ = 'maintenance_records'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.String(50), db.ForeignKey('device.id'), nullable=False)
    time = db.Column(db.DateTime, default=datetime.now)
    content = db.Column(db.String(200))
    type = db.Column(db.String(20))  # primary/success/warning/danger